from PyQt6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QComboBox, QPushButton
import requests

class InboundForm(QWidget):
    """
    入库单录入界面
    - 仓库选择下拉框动态加载仓库数据
    - 提交按钮绑定审核逻辑
    """
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.load_warehouses()

    def setup_ui(self):
        """ 初始化界面组件 """
        self.layout = QVBoxLayout(self)
        self.warehouse_combo = QComboBox()  # 仓库选择
        self.table = QTableWidget()          # 物料录入表格
        self.submit_btn = QPushButton("提交") # 提交按钮
        
        # 表格配置
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(["物料", "数量", "操作"])
        
        # 布局添加组件
        self.layout.addWidget(self.warehouse_combo)
        self.layout.addWidget(self.table)
        self.layout.addWidget(self.submit_btn)
        
        # 绑定事件
        self.submit_btn.clicked.connect(self.submit_order)

    def load_warehouses(self):
        """ 从后端API加载仓库列表 """
        try:
            response = requests.get("http://localhost:8000/api/warehouses/")
            for wh in response.json():
                self.warehouse_combo.addItem(wh["name"], wh["id"])
        except requests.exceptions.ConnectionError:
            print("无法连接到服务器")

    def submit_order(self):
        """ 提交数据到后端API """
        data = {
            "warehouse": self.warehouse_combo.currentData(),
            "details": self.collect_details()
        }
        response = requests.post("http://localhost:8000/api/inbound/", json=data)
        if response.status_code == 201:
            print("入库单提交成功！")